package org.jeecg.modules.assets.service.impl;

import com.alibaba.fastjson.util.TypeUtils;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.assets.entity.AssetsApplyDept;
import org.jeecg.modules.assets.entity.AssetsApplyItem;
import org.jeecg.modules.assets.entity.AssetsInfo;
import org.jeecg.modules.assets.entity.AssetsItem;
import org.jeecg.modules.assets.mapper.AssetsApplyItemMapper;
import org.jeecg.modules.assets.service.IAssetsApplyDeptService;
import org.jeecg.modules.assets.service.IAssetsApplyItemService;
import org.jeecg.modules.assets.service.IAssetsInfoService;
import org.jeecg.modules.assets.service.IAssetsItemService;
import org.jeecg.modules.job.AssetsJob;
import org.jeecg.modules.system.service.impl.SysBaseApiImpl;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Description: 设备申领单管理
 * @Author: jeecg-boot
 * @Date: 2024-11-09
 * @Version: V1.0
 */
@Service
public class AssetsApplyItemServiceImpl extends ServiceImpl<AssetsApplyItemMapper, AssetsApplyItem> implements IAssetsApplyItemService {


    @Autowired
    private IAssetsItemService assetsItemService;
    @Autowired
    private SysBaseApiImpl sysBaseApi;
    @Autowired
    private IAssetsInfoService assetsInfoService;

    @Autowired
    private  AssetsJob assetsJob;
    @Autowired
    private IAssetsApplyDeptService assetsApplyDeptService;
    /**
     * 创建领用单
     *
     * @param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveApply(AssetsApplyItem requesAassetsApplyItem) {

        //根据领用的装备明细，更新领用的库存可用数量
        //判断当前装备状态
        QueryWrapper qw = new QueryWrapper();
        qw.eq("asset_coding", requesAassetsApplyItem.getAssetCoding().substring(requesAassetsApplyItem.getAssetCoding().length() - 6));
        AssetsItem one = assetsItemService.getOne(qw);
        if (one == null) {
            throw new RuntimeException("设备不存在:" + requesAassetsApplyItem.getAssetCoding());
        }
        if (one.getApplyStatus() != 1) {
            throw new RuntimeException("设备，已被领用，请重新选择");
        }

        //开始组装领用单
        AssetsApplyItem assetsApplyItem = new AssetsApplyItem() ;
        BeanUtils.copyProperties(one, assetsApplyItem);
      /*  LoginUser userByName = sysBaseApi.getUserByRealName(assetsApplyItem.getApplyUserId());
        if (userByName.getId() == null) {
            userByName = sysBaseApi.getUserByRealName(assetsApplyItem.getApplyUser());
        }
        if (userByName.getId() == null) {
            throw new RuntimeException("设备，领用人不存在");
        }*/
        //获取当前登录用户
        LoginUser userByName = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        assetsApplyItem.setApplyUserId(userByName.getId());
        assetsApplyItem.setRemark(requesAassetsApplyItem.getRemark());
        one.setApplyStatus(0);
        one.setUserer(userByName.getRealname());
        one.setUsererId(userByName.getId());
        //根据借单位id赋值借用单位名称
        one.setDept(TypeUtils.castToInt(requesAassetsApplyItem.getDept()));
        one.setDeptId(requesAassetsApplyItem.getDeptId());
        assetsApplyItem.setDeptId(requesAassetsApplyItem.getDeptId());
        AssetsApplyDept byId1 = assetsApplyDeptService.getById(requesAassetsApplyItem.getDeptId());
        if (byId1 != null) {
            one.setDeptName(byId1.getDeptName());
            assetsApplyItem.setDeptName(byId1.getDeptName());
            //更新借用单位数量
            byId1.setNum((byId1.getNum()==null? 0 : byId1.getNum()) + 1);
            //todo 推送工具箱
            assetsApplyDeptService.updateById(byId1);
        }

        //更新领用单状态领用中。
        assetsApplyItem.setApplyStatus("1");
        //插入领用单
        assetsApplyItem.setAssetsId(one.getId());
        assetsApplyItem.setApplyDate(DateFormatUtils.format(new java.util.Date(), "yyyy-MM-dd HH:mm:ss"));
        assetsApplyItem.setLender(requesAassetsApplyItem.getLender());
        assetsApplyItem.setId(null);
        save(assetsApplyItem);
        one.setLender(requesAassetsApplyItem.getLender());
        one.setApplyId(assetsApplyItem.getId());
        assetsItemService.updateById(one);
        QueryWrapper one1 = new QueryWrapper();
        one1.eq("asset_name", one.getAssetName());
        //如果借出为损坏资产，则仓库可用数量不变
        AssetsInfo byId = assetsInfoService.getOne(one1);
        if("损坏".equals(one.getStatus())){
            byId.setStoreNum(byId.getStoreNum() - 1);
        }else {
            byId.setStoreUseNum(byId.getStoreUseNum() - 1);
            byId.setStoreNum(byId.getStoreNum() - 1);
        }

        assetsInfoService.updateById(byId);
        /**
         * 领用完成后设备可用数减1
         */
        assetsJob.startWron();
    }

    //设备申领单导入
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importExcel(HttpServletRequest request, HttpServletResponse response) {
        StringBuilder stringBuilder = new StringBuilder();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        Integer count = 0;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<AssetsApplyItem> list = ExcelImportUtil.importExcel(file.getInputStream(), AssetsApplyItem.class, params);
                stringBuilder.append("本次共导入[" + list.size() + "]");
                for (AssetsApplyItem assetsItem : list) {
                    //插入资产明细
                    saveApply(assetsItem);
                    count++;
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("文件导入失败！" + e.getMessage());

            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            stringBuilder.append("成功[" + count + "]");
        }

        return stringBuilder.toString();
    }
}
